# ======================================================================
#
# Copyright (C) ADN
# ADN::SERVER::ParsePID
# Description:
#  - Liste et kill les processus
#  - List and kill process
#
# ======================================================================

package ADN::SERVER::ParsePID;

use strict;
use ADN::LANG::Lang;
use ADN::SERVER::Constant qw(:constant :log);
use ADN::SERVICE::Service;

# #######################
# CREATE OBJECT
# #######################
sub new {
	  my $self = shift;
	  my $class = ref($self) || $self;
	  return $self if ref $self;
	  $self = bless {} => $class;
    %{$self->{lang}} = ADN::LANG::Lang->new()->ParsePID();
		return $self;
}

# #######################
# LANCHER
# #######################
sub start
{
    my $self = shift;
		%{$self->{param}} = @_;
    if ( $self->{param}{Cmd} eq 'kill' ) {
	    @{$self->{return}} = $self->killproc();
    }
    if ( $self->{param}{Cmd} eq 'list' ) {
	    @{$self->{return}} = $self->listproc();
    }
    return @{$self->{return}};
}
# #######################
# KILL PROCESS
# #######################
sub killproc {
    my $self = shift;
    my ( $nbr, $i, $p, $groupe );
    my ( @tab );
    my %service;
    $nbr = scalar @{$self->{param}{Proc}};
    $groupe = $self->{param}{Groupe};
    %service = ADN::SERVICE::Service->new()->$groupe($self->{param}{Name});
    for ( $i = 0; $i < $nbr; $i++ ) {
	   if ( $self->{param}{Proc}[$i] eq '1' || $self->{param}{Proc}[$i] eq '-1' ) {
	    delete $self->{param}{Proc}[$i];
	   }
	   elsif ( defined $self->{param}{Proc}[$i] ) {
	     @tab = split /\//smx, $self->{param}{Proc}[$i];
	     if ($tab[1] eq $self->{param}{ID} && $tab[0] eq $service{function} ) {
		    if ((kill 1, $tab[2]) == 1) {
		      delete $self->{param}{Proc}[$i];
		      $p = 0;
		      last;
		    }
	    }
	   }
	   else { $p = 1; }
   }
   undef %service;
   return @tab if ($p == 0);
	 push @tab, '-1';
	 return @tab; 
}

# #######################
# LIST PROCESS
# #######################
sub listproc {
    my $self = shift;
    my ( $nbr, $i, $check );
    my ( @proc, @tab );
    @proc = @{$self->{param}{Proc}};
    $nbr = scalar @proc;
    for ( $i = 0; $i < $nbr; $i++ ) {
	   if ( $proc[$i] eq '1' || $proc[$i] eq '-1' ) {
	    delete $proc[$i];
	   }
	   @tab = split /\//smx, $proc[$i];
	   $check = kill 0, $tab[2];
	   if ( $check == 0 ) {
	    delete $proc[$i];
	   }
	   if ( defined $proc[$i] ) {
	    $proc[$i] = 'JOB: ' . $tab[0] . ' | ';
	    $proc[$i] .= 'UID: ' . $tab[1] . ' | ';
	    $proc[$i] .= 'PID: ' . $tab[2];
	   }
    }
    $nbr = scalar @proc;
    if ( $nbr == 0 ) {
	   $proc[0] = $self->{lang}{mess1};
    }
    return @proc;
}

# #######################
# DESTROY OBJECT
# #######################
sub DESTROY {
    my $self = shift;
    return;
}
1;
__END__
